package com.one.common.view.pagestate.listpage;

import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.one.common.R;
import com.one.common.common.stateview.EmptyBinder;
import com.one.common.common.stateview.LoadEndBinder;
import com.one.common.common.stateview.item.EmptyItem;
import com.one.common.common.stateview.item.LoadEndItem;
import com.one.common.view.multitytype.ItemViewBinder;
import com.one.common.view.multitytype.MultiTypeAdapter;
import com.one.common.view.pagestate.refreshlayout.IHeaderView;
import com.one.common.view.pagestate.refreshlayout.RefreshListenerAdapter;
import com.one.common.view.pagestate.refreshlayout.TwinklingRefreshLayout;
import com.one.common.view.pagestate.statepage.StatePageInterface;
import com.one.common.view.widget.RecyclerViewNoBugLinearLayoutManager;

import java.util.ArrayList;
import java.util.List;


/**
 * creator: zhulunjun
 * time:    2018/4/9
 * describe: 列表页面数据处理
 * 为了让fragment和activity使用一套逻辑，将对recycleview的操作抽离一个类出来实现，与fragment和activity实现同一个接口
 */

public class ListPageHandle implements ListPageInterface {

    /**
     * 页数
     */
    private int page = 1;
    private RecyclerView mRecyclerView;
    private TwinklingRefreshLayout mRefreshLayout;
    /**
     * 设置头部刷新view的控件
     */
    private View topColorView;
    private MultiTypeAdapter mAdapter;
    private List mItems = new ArrayList<>();
    /**
     * 切换页面状态
     */
    private StatePageInterface mState;
    /**
     * 用于回调实现界面的逻辑
     */
    private ListPageInterface mListPage;
    /**
     * 页面的父view
     * 来获取控件
     */
    private View mView;
    /**
     * 底部view 顶部view
     */
    private LinearLayout bottomView, topView, floatTopView;
    private Context mContext;
    /**
     * 加载状态
     */
    private int loadType = REFRESH;
    /**
     * 刷新状态
     */
    private static final int REFRESH = 1;
    /**
     * 加载更多状态
     */
    private static final int LOAD_MORE = 2;

    /**
     * 是否外部设置隐藏
     */
    private boolean isHindLoadMore = false;

    public ListPageHandle(Context context, View view, StatePageInterface state, ListPageInterface listPage) {
        this.mState = state;
        this.mView = view;
        this.mContext = context;
        this.mListPage = listPage;
    }

    @Override
    public int getLayoutResId() {
        return 0;
    }

    @Override
    public int getSecondLayoutResId() {
        return 0;
    }

    @Override
    public void beforeCreateView() {

    }

    @Override
    public void afterCreateView() {

    }

    @Override
    public boolean haveRootView() {
        return false;
    }

    /**
     * 初始化控件
     */
    public void initView() {
        initList();
        initRefresh();
    }

    @Override
    public void initData() {

    }

    /**
     * 列表初始化
     */
    @SuppressLint("WrongConstant")
    private void initList() {
        mRecyclerView = getView(R.id.rv_list);
        topColorView = getView(R.id.v_top_color);
        if (mRecyclerView == null) {
            return;
        }
        // 是否已经定义过列表样式了
        RecyclerView.LayoutManager layoutManager;
        if (getLayoutManager() == null) {
            RecyclerViewNoBugLinearLayoutManager linearLayoutManager = new RecyclerViewNoBugLinearLayoutManager(mContext);
            linearLayoutManager.setStackFromEnd(getStackFromEnd());
            layoutManager = linearLayoutManager;
        } else {
            layoutManager = getLayoutManager();
        }
        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new MultiTypeAdapter();
        registerDate();
        mAdapter.setItems(mItems);
        mRecyclerView.setAdapter(mAdapter);
    }

    @Override
    public RecyclerView.LayoutManager getLayoutManager() {
        return mListPage.getLayoutManager();
    }

    @Override
    public void setHeadView(IHeaderView headerView) {
        mRefreshLayout.setHeaderView(headerView);
    }

    @Override
    public void setHeaderColor(int color) {
        topColorView.setBackgroundColor(color);
    }

    private boolean mIsRefreshing;

    /**
     * 刷新控件初始化
     */
    private void initRefresh() {
        mRefreshLayout = getView(R.id.tr_refresh);
        if (mRefreshLayout == null) {
            return;
        }
//        mRefreshLayout.setFloatRefresh(true);
        mRecyclerView.setOnTouchListener((view, motionEvent) -> {
            if (mIsRefreshing) {
                return true;
            } else {
                return false;
            }
        });

        mRefreshLayout.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                mIsRefreshing = true;
                doRefresh();
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                doLoadMore();
            }
        });

//        mRefreshLayout.setHeaderView(new MyHeaderView(mContext));
//        mRefreshLayout.setBottomView(new MyFooterView(mContext));

    }

    /**
     * 初始化底部自定義控件
     */
    private void initBottom(int bottomResId) {
        bottomView = getView(R.id.ll_bottom_view);
        if (bottomView != null && bottomResId != -1) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View view = inflater.inflate(bottomResId, bottomView, false);
            bottomView.addView(view);
        }
    }

    /**
     * 初始化顶部自定義控件
     */
    private void initTop(int topRes) {
        topView = getView(R.id.ll_top_view);
        if (topView != null && topRes != -1) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View view = inflater.inflate(topRes, topView, false);
            topView.addView(view);
        }
    }

    /**
     * 初始化顶部自定義控件 悬浮
     */
    private void initFloatTop(int topRes) {
        floatTopView = getView(R.id.ll_float_top_view);
        if (floatTopView != null && topRes != -1) {
            LayoutInflater inflater = LayoutInflater.from(mContext);
            View view = inflater.inflate(topRes, floatTopView, false);
            floatTopView.addView(view);
        }
    }

    @Override
    public void registerDate() {
        // 此处需要最终的实现页面来调用
        mListPage.registerDate();
    }

    @Override
    public void refresh() {
        // 主动刷新
        mRefreshLayout.startRefresh();
    }

    @Override
    public void doRefresh() {
        loadType = REFRESH;
        page = 1;
//        mItems.clear();
//        mAdapter.notifyDataSetChanged();
        if (!isHindLoadMore) {
            showLoadMore();
        }
        loadData();

    }

    @Override
    public void loadMore() {
        // 主动加载更多
        mRefreshLayout.startLoadMore();
    }

    @Override
    public void doLoadMore() {
        page++;
        loadData();
        loadType = LOAD_MORE;
    }

    @Override
    public void loadData() {
        // 此处需要最终的实现页面来调用
        mListPage.loadData();
    }

    @Override
    public void loadSuccess(List<?> data) {
        if (null == data || data.size() == 0) {
            if (page == 1) {
                mItems.clear();
                mAdapter.notifyDataSetChanged();

                // 没数据
                if (mState.onEmpty()) {
                    // 子类自己处理
                    mState.success();
                } else {
                    mState.empty();
                }
            } else {
                // 数据加载完成
                addData(new LoadEndItem());
                if (mRefreshLayout != null) {
                    mRefreshLayout.setEnableLoadmore(false);
                }
            }

        } else {
            mState.success();
            // 展示数据
            if (loadType == REFRESH) {
                refreshSize = 0;
                replaceData(data);
            } else {
                refreshSize = data.size();
                mItems.addAll(data);
            }

        }
        endLoad();

    }

    /**
     * 是刷新，还是增加数据
     */
    private int refreshSize = 0;

    @Override
    public void loadFail(String errorMessage) {
        mState.error(errorMessage);
        endLoad();
    }

    @Override
    public void replaceData(List<?> data) {
        if (null != data) {
            mItems = data;
            mAdapter.setItems(data);
        }
        mIsRefreshing = false;
    }

    @Override
    public void addData(Object o) {
        if (o != null) {
            mItems.add(o);
            mAdapter.notifyItemChanged(mItems.size() - 1);
        }
        mIsRefreshing = false;
    }

    @Override
    public void addData(int index, Object o) {
        if (index >= 0 && o != null) {
            mItems.add(index, o);
            mAdapter.notifyItemRangeChanged(index, mItems.size() - index);
        }
        mIsRefreshing = false;
    }

    @Override
    public void deleteData(Object o) {
        if (o != null) {
            int index = mItems.indexOf(o);
            mItems.remove(o);
            mAdapter.notifyItemRemoved(index);
        }
    }

    @Override
    public void deleteData(int index) {
        if (index > -1) {
            mItems.remove(index);
            mAdapter.notifyItemRemoved(index);
        }
    }


    @Override
    public void addBottomView(int resId) {
        initBottom(resId);
    }

    @Override
    public void addTopView(int resId) {
        initTop(resId);
    }

    @Override
    public void addFloatTopView(int resId) {
        initFloatTop(resId);
    }


    @Override
    public void hindLoadMore() {
        if (mRefreshLayout != null) {
            isHindLoadMore = true;
            mRefreshLayout.setEnableLoadmore(false);
        }
    }

    public void showLoadMore() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setEnableLoadmore(true);
        }
    }

    public void showRefresh(){
        if (mRefreshLayout != null) {
            mRefreshLayout.setEnableRefresh(true);
        }
    }

    @Override
    public void hindRefresh() {
        if (mRefreshLayout != null) {
            mRefreshLayout.setEnableRefresh(false);
        }
    }

    @Override
    public boolean getStackFromEnd() {
        return mListPage.getStackFromEnd();
    }

    @Override
    public List<?> getData() {
        return mItems;
    }

    @Override
    public RecyclerView getListView() {
        return mRecyclerView;
    }

    @Override
    public TwinklingRefreshLayout getRefresh() {
        return mRefreshLayout;
    }

    @Override
    public int getPage() {
        return page;
    }

    @Override
    public MultiTypeAdapter getAdapter() {
        return mAdapter;
    }


    /**
     * 获取控件
     *
     * @param viewId 控件id
     * @param <T>    类型
     * @return 控件
     */
    public <T extends View> T getView(@IdRes int viewId) {
        return (T) mView.findViewById(viewId);
    }

    /**
     * 结束加载
     */
    private void endLoad() {
        if (loadType == REFRESH) {
            mRefreshLayout.finishRefreshing();
        } else {
            mRefreshLayout.finishLoadmore();
        }
        if (refreshSize == 0) {
            mAdapter.notifyDataSetChanged();
        } else {
            mAdapter.notifyItemRangeChanged(refreshSize, getData().size());
        }

    }

    /**
     * 注册数据
     *
     * @param clazz  数据模型
     * @param binder 绑定视图的适配器
     */
    public <T> void register(@NonNull Class<? extends T> clazz, @NonNull ItemViewBinder<T, ?> binder) {
        mAdapter.register(clazz, binder);
        mAdapter.register(EmptyItem.class, new EmptyBinder());
        mAdapter.register(LoadEndItem.class, new LoadEndBinder());
    }


    //********页面需要实现的**********//

    @Override
    public void success() {

    }

    @Override
    public void setEmptyStr(String emptyStr) {

    }

    @Override
    public void setEmptyRes(int emptyRes) {

    }

    @Override
    public void empty() {

    }

    @Override
    public void empty(String emptyStr) {

    }

    @Override
    public void empty(int imageRes, String emptyStr) {

    }

    @Override
    public void setEmptyView(View view) {

    }

    @Override
    public void error() {

    }

    @Override
    public void error(String errorStr) {

    }

    @Override
    public void error(int imageRes, String errorStr) {

    }

    @Override
    public void setErrorView(View view) {

    }

    @Override
    public void loading() {

    }

    @Override
    public void setLoadingView(View view) {

    }

    @Override
    public void onEmptyClick() {

    }

    @Override
    public void onErrorClick() {

    }

    @Override
    public boolean onEmpty() {
        return false;
    }

    @Override
    public boolean onError() {
        return false;
    }

    @Override
    public void showToast(String msg) {

    }

    @Override
    public void finishPage() {

    }

    @Override
    public void showLoading() {

    }

    @Override
    public void cancelLoading() {

    }
}
